package com.wenx.v3system.modular.platform.service.remote;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wenx.v3core.response.R;
import com.wenx.v3openfeign.api.PlatformUserRemoteInfra;
import com.wenx.v3openfeign.dto.PlatformUserAuthInfoDto;
import com.wenx.v3system.modular.platform.domain.dto.PlatformUserAuthRequestDto;
import com.wenx.v3system.modular.platform.domain.dto.PlatformUserAuthResultDto;
import com.wenx.v3system.modular.platform.domain.po.PlatformUser;
import com.wenx.v3system.modular.platform.service.PlatformUserAuthService;
import com.wenx.v3system.modular.platform.service.PlatformUserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.function.Function;

/**
 * 平台用户远程服务实现类
 * 实现PlatformUserRemoteInfra接口，提供平台用户相关的远程服务
 * 
 * @author wenx
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class PlatformUserRemoteInfraImpl implements PlatformUserRemoteInfra {

    private final PlatformUserService platformUserService;
    private final PlatformUserAuthService platformUserAuthService;

    @Override
    public R getPlatformUserAuthInfo(String identifier) {
        log.debug("根据标识符获取平台用户认证信息: identifier={}", identifier);
        
        if (StrUtil.isBlank(identifier)) {
            return R.failed("用户标识符不能为空");
        }
        
        try {
            // 按优先级尝试不同的查询方式：用户名 > 邮箱 > 手机号
            R result = getPlatformUserAuthInfoByUsername(identifier);
            if (isSuccessResult(result)) {
                log.debug("通过用户名查询成功: identifier={}", identifier);
                return result;
            }
            
            result = getPlatformUserAuthInfoByEmail(identifier);
            if (isSuccessResult(result)) {
                log.debug("通过邮箱查询成功: identifier={}", identifier);
                return result;
            }
            
            result = getPlatformUserAuthInfoByPhone(identifier);
            if (isSuccessResult(result)) {
                log.debug("通过手机号查询成功: identifier={}", identifier);
                return result;
            }
            
            log.warn("平台用户不存在: identifier={}", identifier);
            return R.failed("平台用户不存在");
            
        } catch (Exception e) {
            log.error("根据标识符获取平台用户认证信息失败: identifier={}", identifier, e);
            return R.failed("获取平台用户信息失败");
        }
    }

    @Override
    public R getPlatformUserAuthInfoByUsername(String username) {
        return queryUserByField(username, "用户名", 
            wrapper -> wrapper.eq(PlatformUser::getUsername, username));
    }

    @Override
    public R getPlatformUserAuthInfoByEmail(String email) {
        return queryUserByField(email, "邮箱地址", 
            wrapper -> wrapper.eq(PlatformUser::getEmail, email));
    }

    @Override
    public R getPlatformUserAuthInfoByPhone(String phone) {
        return queryUserByField(phone, "手机号", 
            wrapper -> wrapper.eq(PlatformUser::getPhone, phone));
    }

    /**
     * 通用的用户查询方法
     */
    private R queryUserByField(String fieldValue, String fieldName, 
            Function<LambdaQueryWrapper<PlatformUser>, LambdaQueryWrapper<PlatformUser>> queryBuilder) {
        log.debug("根据{}获取平台用户认证信息: {}={}", fieldName, fieldName, fieldValue);
        
        if (StrUtil.isBlank(fieldValue)) {
            return R.failed(fieldName + "不能为空");
        }
        
        try {
            LambdaQueryWrapper<PlatformUser> wrapper = queryBuilder.apply(createBaseQuery());
            return processUserQuery(wrapper, fieldName, fieldValue);
            
        } catch (Exception e) {
            log.error("根据{}获取平台用户认证信息失败: {}={}", fieldName, fieldName, fieldValue, e);
            return R.failed("获取用户认证信息失败");
        }
    }

    /**
     * 创建基础查询条件（只查询启用状态的用户）
     */
    private LambdaQueryWrapper<PlatformUser> createBaseQuery() {
        return new LambdaQueryWrapper<PlatformUser>()
            .eq(PlatformUser::getStatus, 1)
            .eq(PlatformUser::getDeleted, 0);
    }

    /**
     * 处理平台用户查询的通用逻辑
     */
    private R processUserQuery(LambdaQueryWrapper<PlatformUser> wrapper, String queryType, String queryValue) {
        PlatformUser user = platformUserService.getOne(wrapper);
        if (user == null) {
            log.warn("平台用户不存在: {}={}", queryType, queryValue);
            return R.failed("平台用户不存在");
        }

        PlatformUserAuthInfoDto authInfo = buildUserAuthInfo(user);
        log.debug("平台用户认证信息获取成功: {}={}, userId={}", queryType, queryValue, user.getId());
        return R.ok(authInfo);
    }

    /**
     * 构建完整的平台用户认证信息
     */
    private PlatformUserAuthInfoDto buildUserAuthInfo(PlatformUser user) {
        PlatformUserAuthInfoDto authInfo = new PlatformUserAuthInfoDto();
        
        // 基本用户信息
        BeanUtils.copyProperties(user, authInfo);

        // 加载权限和角色信息
        loadPermissionsAndRoles(user.getId(), authInfo);
        
        return authInfo;
    }

    /**
     * 加载用户的权限和角色信息
     */
    private void loadPermissionsAndRoles(Long userId, PlatformUserAuthInfoDto authInfo) {
        try {
            authInfo.setPermissions(getDataOrDefault(getPlatformUserPermissions(userId)));
            authInfo.setRoleCodes(new ArrayList<>(getDataOrDefault(getPlatformUserRoles(userId))));
        } catch (Exception e) {
            log.warn("加载用户权限角色信息失败: userId={}", userId, e);
            authInfo.setPermissions(new HashSet<>());
            authInfo.setRoleCodes(new ArrayList<>());
        }
    }

    /**
     * 获取结果数据或返回默认空集合
     */
    private Set<String> getDataOrDefault(R result) {
        return (isSuccessResult(result) && result.getData() instanceof Set) 
            ? (Set<String>) result.getData() 
            : new HashSet<>();
    }

    @Override
    public R getPlatformUserPermissions(Long userId) {
        return executeWithUserIdValidation(userId, "获取平台用户权限", () -> {
            List<String> permissionList = platformUserService.getUserPermissions(userId);
            Set<String> permissions = new HashSet<>(permissionList);
            log.debug("平台用户权限获取成功: userId={}, permissionCount={}", userId, permissions.size());
            return R.ok(permissions);
        });
    }

    @Override
    public R getPlatformUserRoles(Long userId) {
        return executeWithUserIdValidation(userId, "获取平台用户角色", () -> {
            List<String> roles = platformUserService.getUserRoles(userId);
            log.debug("平台用户角色获取成功: userId={}, roleCount={}", userId, roles.size());
            return R.ok(roles);
        });
    }

    @Override
    public R getPlatformUserMenus(Long userId) {
        return executeWithUserIdValidation(userId, "获取平台用户菜单", () -> {
            List<String> menus = platformUserService.getUserMenuCodes(userId);
            log.debug("平台用户菜单获取成功: userId={}, menuCount={}", userId, menus.size());
            return R.ok(menus);
        });
    }

    @Override
    public R isPlatformAccountActive(Long userId) {
        return executeWithUserIdValidation(userId, "验证平台用户账户状态", () -> {
            PlatformUser user = platformUserService.getById(userId);
            if (user == null) {
                log.warn("平台用户不存在: userId={}", userId);
                return R.ok(false);
            }
            
            boolean isActive = user.getStatus() != null && user.getStatus() == 1 && user.getDeleted() == 0;
            log.debug("平台用户账户状态验证完成: userId={}, isActive={}", userId, isActive);
            return R.ok(isActive);
        });
    }

    @Override
    public R getPlatformUserAccessibleTenants(Long userId) {
        return executeWithUserIdValidation(userId, "获取平台用户可访问租户", () -> {
            List<String> accessibleTenants = platformUserService.getUserAccessibleTenants(userId);
            log.debug("平台用户可访问租户获取成功: userId={}, tenantCount={}", userId, accessibleTenants.size());
            return R.ok(accessibleTenants);
        });
    }

    /**
     * 通用的用户ID验证和执行方法
     */
    private R executeWithUserIdValidation(Long userId, String operation, java.util.function.Supplier<R> action) {
        log.debug("{}: userId={}", operation, userId);
        
        if (userId == null) {
            return R.failed("用户ID不能为空");
        }
        
        try {
            return action.get();
        } catch (Exception e) {
            log.error("{}失败: userId={}", operation, userId, e);
            return R.failed(operation + "失败");
        }
    }

    @Override
    public R authenticatePlatformUser(String identifier, String password) {
        log.debug("平台用户认证: identifier={}", identifier);
        
        if (StrUtil.isBlank(identifier) || StrUtil.isBlank(password)) {
            return R.failed("用户名和密码不能为空");
        }
        
        try {
            PlatformUserAuthRequestDto authRequest = new PlatformUserAuthRequestDto();
            authRequest.setIdentifier(identifier);
            authRequest.setPassword(password);
            
            PlatformUserAuthResultDto authResult = platformUserAuthService.authenticate(authRequest);
            
            if (authResult.getSuccess()) {
                log.debug("平台用户认证成功: identifier={}", identifier);
                return R.ok(authResult);
            } else {
                log.warn("平台用户认证失败: identifier={}, reason={}", identifier, authResult.getFailureReason());
                return R.failed(authResult.getFailureReason());
            }
            
        } catch (Exception e) {
            log.error("平台用户认证失败: identifier={}", identifier, e);
            return R.failed("认证失败");
        }
    }

    /**
     * 判断结果是否成功
     */
    private boolean isSuccessResult(R result) {
        return result != null && result.getCode() == 0L && result.getData() != null;
    }
}